import * as fs from "fs";
import * as http from "http";

const url = "http://localhost:8900/downloadFile?file=ad2.mp4";

// 发送请求
const request = http.get(url, response => {
  const contentType = response.headers["content-cype"];
  console.log("contentType: ", contentType);
  const contentLength = parseInt(response.headers["content-length"] || "-1");
  let downLen = 0;

  const ws = fs.createWriteStream(`./hello.mp4`);
  response.pipe(ws);
  response.on("data", chunk => {
    downLen += chunk.length;
    const precent = (downLen / contentLength) * 100;
    console.log(`下载进度: ${precent.toFixed(2)}%`);
  });

  response.on("end", () => {
    console.log(`下载完成`);
  });
});

request.on("error", err => {
  console.log(`下载文件出错: `, err);
});